package com.wsc.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wsc.service.StatisticsService;

import net.sf.json.JSONObject;

@RequestMapping("/statistics")
@RestController
@CrossOrigin // 跨域访问
@EnableScheduling//标注启动定时执行
public class StatisticsController {
	@Autowired
	private StatisticsService ss;

	@RequestMapping("/getAll")
	public Map<String, Object> getAll(Integer readroomid, Integer page, Integer limit) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("readroomid", readroomid);
		limit = limit == null ? 10 : limit;
		page = page == null ? 0 : page - 1;
		params.put("limit", limit);
		params.put("page", page);
		return ss.getAll(params);
	}
	//生成图表所需数据 membertype指学生还是教师或者所有人员
	@RequestMapping("/getChartData")
	public Map<String, Object> getChartData(String intime, String outtime) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> names = new ArrayList<String>();
		List<Integer> nums = new ArrayList<Integer>();
		// 饼图专用
		List<JSONObject> objects = new ArrayList<JSONObject>();
		//数据库判断无法判断空字符，会造成Date >= "" and Date <= ""的条件查询
		if(intime.equals("")) {
			intime = null;
		}
		if(outtime.equals("")) {
			outtime = null;
		}
		// 原生sql获取数据 intime,outtime,membertype
		List<Object[]> list = ss.getChartData(intime, outtime);
		// 添加map集合
		for (int i = 0; i < list.size(); i++) {
			String name = (String) list.get(i)[0];
			// 原生sql count(*)查询结果类型为BigInteger
			Integer value = Integer.parseInt(list.get(i)[1].toString());
			names.add(name);
			nums.add(value);
			// 新建json对象 添加对象属性
			JSONObject object = new JSONObject();
			object.put("name", name);
			object.put("value", value);
			// 添加到数组
			objects.add(object);
		}
		map.put("names", names);
		map.put("nums", nums);
		map.put("objects", objects);
		return map;
	}
	/***
	 * 定时任务  每天晚上10点执行
	 * 在每天固定时间查询ConsumeLogs表,统计出不同图书馆的使用次数，在Statistics表进行循环插入数据.
	 */
	@Scheduled(cron = "0 * 22 * * ?")
	public void addFromConsumeLogToStatistics() {
		ss.addFromConsumeLogToStatistics();
	}
}
